package com.jielin.handling.service.goods.impl;

import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.github.pagehelper.PageHelper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.jielin.handling.entity.goods.Belongings;
import com.jielin.handling.entity.tsuspect.TSuspec;
import com.jielin.handling.exception.ResultEnum;
import com.jielin.handling.mapper.goods.BelongingsMapper;
import com.jielin.handling.mapper.police.PoliceManMapper;
import com.jielin.handling.mapper.record.RecordDetailedMapper;
import com.jielin.handling.mapper.tsuspect.TSuspecMapper;
import com.jielin.handling.service.goods.GoodsService;
import com.jielin.handling.service.xsky.XskyService;
import com.jielin.handling.util.ConstantUtil;
import com.jielin.handling.util.StringUtil;
import com.jielin.handling.util.pdfutil.Watermark;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * Created by wangjienice on 2019/3/19.
 */
@Service
@Slf4j
public class GoodsServiceImpl implements GoodsService {
    private static Font headfont;// 设置字体大小
    private static Font keyfont;// 设置字体大小
    private static Font textfont;// 设置字体大小
    private static Font font;// 设置字体大小
    private static Font minimumFont;


    @Autowired
    BelongingsMapper belongingsMapper;
    @Autowired
    TSuspecMapper tSuspecMapper;
    @Autowired
    PoliceManMapper policeManMapper;
    @Autowired
    private XskyService xskyService;
    @Autowired
    private RecordDetailedMapper recordDetailedMapper;

    // draw cell line
    private static void drawLine(PdfContentByte canvas, float left, float top, float x, float y) {
        canvas.saveState();
        canvas.moveTo(left, top);
        canvas.lineTo(left + x, top - y);
        canvas.stroke();
        canvas.restoreState();
    }

    static {
        BaseFont bfChinese;
        try {
            // bfChinese =
            // BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            // Font.BOLD：加粗
            // Font.BOLDITALIC：斜体、加粗
            // Font.DEFAULTSIZE：中划线、下划线
            // Font.ITALIC：斜体
            // Font.NORMAL：没有样式
            // Font.STRIKETHRU：中划线
            // Font.UNDEFINED：没有样式
            // Font.UNDERLINE：下划线
            headfont = new Font(bfChinese, 25, Font.BOLD);// 设置字体大小
            keyfont = new Font(bfChinese, 15, Font.UNDERLINE);// 设置字体大小
            textfont = new Font(bfChinese, 15, Font.NORMAL);// 设置字体大小
            font = new Font(bfChinese, 12, Font.NORMAL);// 设置字体大小
            minimumFont = new Font(bfChinese, 8, Font.NORMAL);// 设置字体大小
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Belongings> selectAll(Belongings belongings) {
        List<Belongings> list = null;
        try {
            PageHelper.startPage(belongings.getPageNum(), belongings.getPageSize());
            list = belongingsMapper.selectAll(belongings);
            for (Belongings good : list) {
                if (!ConstantUtil.XSKYRESTORAGE) {
                    String returnPath = ConstantUtil.SERVER_URL + good.getPicUrl();
                    good.setPicUrl(returnPath);
                }

            }
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;


    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int addGoods(Belongings belongings) {
        log.info("service 事务测试start...");
        TSuspec tSuspec = new TSuspec();
        try {
            tSuspec.setId(belongings.getSuspectId());
            TSuspec suspectState = tSuspecMapper.selectStatue(belongings.getSuspectId());
            if (!"8".equals(suspectState.getSuspectState())) {
                tSuspec.setSuspectState("3");
            } else {
                tSuspec.setSuspectState(suspectState.getSuspectState());
            }

            tSuspecMapper.updateState(tSuspec);
            return belongingsMapper.insert(belongings);
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            //抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
    }

    @Override
    public int delGoods(String id) {
        return belongingsMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int upDateGoods(String filePath, String id) {

        return belongingsMapper.upDateGoods(filePath, id);
    }

    @Override
    public int upDateVdieoGoods(String path, String id) {

        return belongingsMapper.upDateVdieoGoods(path, id);
    }

    @Override
    public int upDateZkGoods(String id) {
        return belongingsMapper.upDateZkGoods(id);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int updateByPrimaryKey(Belongings belongings) {
        TSuspec tSuspec = new TSuspec();
        try {
            tSuspec.setId(belongings.getSuspectId());
            tSuspec.setSuspectState("7");
            tSuspecMapper.updateState(tSuspec);
            return belongingsMapper.updateByPrimaryKey(belongings);
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            //抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public Belongings selectById(String id) {
        try {
            Belongings belongings = belongingsMapper.selectById(id);
            belongings.setRecordVideoPath(recordDetailedMapper.findVideoByBelongingsId(id));
            if(belongings.getTakeType()==0){
                String suspectId = belongings.getSuspectId();
                TSuspec suspec = tSuspecMapper.selectById(suspectId);
                belongings.setTakeName(suspec.getName());
                belongings.setTakeIdentity(suspec.getIdValue());
            }
            if (!StringUtil.isEmpty(belongings.getPicUrl()) && !ConstantUtil.XSKYRESTORAGE) {
                //返回给前台的图片路径，nginx地址，端口，，nginx映射，数据库存储路径
                String returnPath = ConstantUtil.SERVER_URL + belongings.getTakePhoto();
                belongings.setPicUrl(returnPath);
            }
            return belongings;
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            //抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
    }

    @Override
    public String goodsPrintByType(Belongings belongings) {
        List<Belongings> list = null;
        list = belongingsMapper.selectAllByType(belongings);


        // 1.
        // 第一个参数是页面大小。接selectAllByType下来的参数分别是左、右、上和下页边距。
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        // 2.建立一个书写器(Writer)与document对象关联，通过书写器(Writer)可以将文档写入到磁盘中。
        // 创建 PdfWriter 对象 第一个参数是对文档对象的引用，第二个参数是文件的实际名称，在该名称中还会给出其输出路径。
        String path = ConstantUtil.ROOT_PATH + "goodspdfs";
        File goodspdfs = new File(path);
        if (!goodspdfs.exists() && !goodspdfs.isDirectory()) {
            log.info("目录或文件不存在！");
            goodspdfs.mkdir();
        }
        // pdf文件存储路径
        String PdfWriterpath = path + File.separatorChar + StringUtil.generatorUUID() + "goods.pdf";
        String returnPath = "";
        //pdf返回的pdf存储路径
        if (!ConstantUtil.XSKYRESTORAGE) {
            returnPath = ConstantUtil.PDF_PATH + PdfWriterpath;//返回pdf服务器存储路径
            System.out.println("returnPath>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + returnPath);
        }

        try {
            String suspectId = belongings.getSuspectId();
            String organizationName = belongingsMapper.selectOrgnizationNameById(suspectId);

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PdfWriterpath));
            log.info(PdfWriterpath);

            // 加水印
            writer.setPageEvent(new Watermark(organizationName));//设置水印为单位名称

            // 打开文档
            document.open();
            // 1标题
            if (belongings.getKeepMethed().equals("0")) {

                Chunk text1 = new Chunk(organizationName + "扣押物品,文件清单");
                Phrase titlep = new Phrase();
                titlep.setFont(headfont);
                titlep.add(text1);
                //2设置标题居中
                Paragraph pt = new Paragraph();
                pt.setAlignment(1);// 设置文字居中 0靠左 1，居中 2，靠右
                pt.add(titlep);
                document.add(pt);
            }
            if (belongings.getKeepMethed().equals("1")) {
                Chunk text1 = new Chunk(organizationName + "返还物品,文件清单");
                Phrase titlep = new Phrase();
                titlep.setFont(headfont);
                titlep.add(text1);
                //2设置标题居中
                Paragraph pt = new Paragraph();
                pt.setAlignment(1);// 设置文字居中 0靠左 1，居中 2，靠右
                pt.add(titlep);
                document.add(pt);
            } else {
                Chunk text1 = new Chunk(organizationName + "收缴物品,文件清单");
                Phrase titlep = new Phrase();
                titlep.setFont(headfont);
                titlep.add(text1);
                //2设置标题居中
                Paragraph pt = new Paragraph();
                pt.setAlignment(1);// 设置文字居中 0靠左 1，居中 2，靠右
                pt.add(titlep);
                document.add(pt);
            }

            //生成5列表格
            PdfPTable table = new PdfPTable(5);
            //设置每一列所占的长度
            table.setWidths(new float[]{10f, 20f, 20f, 10f, 15f});
            table.setSpacingBefore(5);
            table.setPaddingTop(5);
            //设置表格具体宽度
            table.setTotalWidth(75);

            //==================================================================
            PdfPCell[] cellHeaders = new PdfPCell[5];
            cellHeaders[0] = new PdfPCell(new Phrase("编号", font));
            cellHeaders[1] = new PdfPCell(new Phrase("照片 ", font));
            cellHeaders[2] = new PdfPCell(new Phrase("物品名称", font));
            cellHeaders[3] = new PdfPCell(new Phrase("数量", font));
            cellHeaders[4] = new PdfPCell(new Phrase("物品特征", font));
            // cellHeaders[5] = new PdfPCell(new Phrase("处理情况", font));
            /** 向表格填充数据 author:yyli Sep 15, 2010 */
            for (int i = 0; i < cellHeaders.length; i++) {
                /** 居中显示 author:yyli Sep 15, 2010 */
                cellHeaders[i].setHorizontalAlignment(Element.ALIGN_CENTER);
                /** 纵向居中显示 author:yyli Sep 15, 2010 */
                cellHeaders[i].setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cellHeaders[i]);
            }
            //=================================================================
            for (int i = 0; i < list.size(); i++) {
                /** 第0列 author:yyli Sep 15, 2010 */
                //填充第一列的编号并设置字体
                PdfPCell cell0 = new PdfPCell(new Phrase(String.valueOf(i + 1), font));
                cell0.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell0.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell0);
                //=================================================================
                //从第2列到第五列一次开始填充数据
                PdfPCell[] cell2_5 = new PdfPCell[4];
//                // 读取图片(参数为gif、jpg、png格式的图片都可以)，设置图片大小
//                Image image = Image.getInstance("D:/test/1.jpg");
//                // 设置图片的绝对大小，宽和高
//                image.scaleAbsolute(50f, 50f);
//                // 设置图片居中显示
//                image.setAlignment(Image.MIDDLE);
                //=====================================================================
                //cell2_5[0] = new PdfPCell(new Phrase(list.get(i).getPicUrl(), font));
                String photoPath = list.get(i).getPicUrl();
                if (!StringUtil.isEmpty(photoPath)) {
                    String headPicture = ConstantUtil.PHOTO_PATH + photoPath;
                    Image image = ConstantUtil.XSKYRESTORAGE ? Image.getInstance(new URL(photoPath)) :
                            Image.getInstance(headPicture);
                    // 设置图片居中显示
                    image.setAlignment(Image.MIDDLE);
                    image.scaleAbsolute(33f, 33f);
                    cell2_5[0] = new PdfPCell(image);
                }
                cell2_5[1] = new PdfPCell(new Phrase(list.get(i).getGoodsName(), font));
                cell2_5[2] = new PdfPCell(new Phrase(String.valueOf(list.get(i).getAmount()), font));
                cell2_5[3] = new PdfPCell(new Phrase(list.get(i).getEffectsDescribe(), font));
                //给后五列设置字符集
                for (int n = 0; n < cell2_5.length; n++) {
                    cell2_5[n].setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell2_5[n].setVerticalAlignment(Element.ALIGN_MIDDLE);
                    //设置每个单元格的高度
                    cell2_5[n].setFixedHeight(50);
                    table.addCell(cell2_5[n]);
                }

            }
            //========================================================================================================================表格斜线
            //坐标起始位置
            float LEFT = document.left() + 50f;//表格起点x轴坐标
            float top = document.top() - list.size() * 50 - 37;//起点y轴坐标
            //坐标终点位置
            float x = document.right() - 150f;//表格终点x轴坐标
            float y = 450;//表格终点y坐标
            System.out.print(y + "------------------=========================-------------------------------");
            // int y=100+list.size()*50;
            int z = 50;//每列单元格高度
            float p = document.bottom() - top;//起点位置和终点位置,以便于填充高度为50的单元格

            for (int j = 0; j < (y / 50) * 5; j++) {
                PdfPCell cell1 = new PdfPCell();
                cell1 = new PdfPCell(new Phrase("", font));
                cell1.setFixedHeight(50);
                table.addCell(cell1);
            }

            PdfContentByte canvas = writer.getDirectContent();
            drawLine(canvas, LEFT, top, x, y);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String Date = sdf.format(new Date());
            //=================================================================最后一列中文
            PdfPCell cell11 = new PdfPCell(new Phrase("物品,文件持有人", minimumFont));
            cell11.setFixedHeight(50);
            cell11.setColspan(5);
            cell11.setRowspan(5);
            table.addCell(cell11);

//            cellLow1.setColspan(5);
//            cellLow1.setFixedHeight(10);
//            cellLow1.
//            //左边的cell
//            cellLow.setBorderWidthRight(0);    //边框宽度
//            cellLow.setBorderWidthLeft(1);    //边框宽度
//            cellLow.setBorderWidthBottom(1);    //边框宽度
//            cellLow.setBorderWidthTop(1);    //边框宽度
//
//            cellLow.setFixedHeight(20);
//            cellLow.setColspan(5);
//            table.addCell(cellLow);
//            //==================================================================右下角时间设置
//            PdfPCell cellRight = new PdfPCell(new Phrase(Date, minimumFont));
//            //左边的cell
//            cellRight.setBorderWidthRight(1);    //边框宽度
//            cellRight.setBorderWidthLeft(0);    //边框宽度
//            cellRight.setBorderWidthBottom(1);    //边框宽度
//            cellRight.setBorderWidthTop(1);    //边框宽度
//            cellRight.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); //水平偏右
//            cellRight.setVerticalAlignment(PdfPCell.ALIGN_BOTTOM); //垂直居底
//            cellRight.setBorderWidth(0);
//            cellRight.setFixedHeight(20);
//            cellRight.setColspan(5);
//            table.addCell(cellRight);

            document.add(table);
            //document.add(new Paragraph("11111111111111111111"));
            document.close();
            writer.close();

        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        log.info("wan>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        return returnPath;


    }

    @Override
    public List<Belongings> selectGoods(String policeId) {
        log.info("policeId:{}", JSONObject.toJSONString(policeId));
        List<Belongings> lists = belongingsMapper.selectGoods(policeId);
        for (Belongings belongings : lists) {
            if (!ConstantUtil.XSKYRESTORAGE) {
                String returnPath = ConstantUtil.SERVER_URL + belongings.getPicUrl();
                belongings.setPicUrl(returnPath);
            }

        }
        return lists;
    }

    @Override
    public int updateSuspectGoods(Belongings belongings) {
        return belongingsMapper.updateSuspectGoods(belongings);

    }

    @Override
    public String selectAllByType(Belongings belongings) {
        List<Belongings> list = null;

        // 1.新建document对象
        // 第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        // 2.建立一个书写器(Writer)与document对象关联，通过书写器(Writer)可以将文档写入到磁盘中。
        // 创建 PdfWriter 对象 第一个参数是对文档对象的引用，第二个参数是文件的实际名称，在该名称中还会给出其输出路径。
        String path = ConstantUtil.ROOT_PATH + "goodspdfs";
        File goodspdfs = new File(path);
        if (!goodspdfs.exists() && !goodspdfs.isDirectory()) {
            log.info("目录或文件不存在！");
            goodspdfs.mkdir();
        }
        // pdf文件存储路径
        String PdfWriterpath = path + File.separatorChar + StringUtil.generatorUUID() + "goods.pdf";
        String returnPath = "";
        if (!ConstantUtil.XSKYRESTORAGE) {
            returnPath = ConstantUtil.PDF_PATH + PdfWriterpath;//返回pdf服务器存储全路径
            System.out.println("returnPath>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>." + returnPath);
        }
        try {
            String suspectId = belongings.getSuspectId();
            String organizationName = belongingsMapper.selectOrgnizationNameById(suspectId);
            belongings.setPoliceName(policeManMapper.findNameBySuspectId(suspectId));
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PdfWriterpath));
            list = belongingsMapper.selectAllByType(belongings);
            log.info(PdfWriterpath);

            // 加水印
            writer.setPageEvent(new Watermark(organizationName));//设置水印为单位名称

            // 打开文档
            document.open();

            // 1标题
            Chunk text1 = new Chunk(organizationName + "处理物品,文件清单");
            Phrase titlep = new Phrase();
            titlep.setFont(headfont);
            titlep.add(text1);
            //2设置标题居中
            Paragraph pt = new Paragraph();
            pt.setAlignment(1);// 设置文字居中 0靠左 1，居中 2，靠右
            pt.add(titlep);
            document.add(pt);

            //生成6列表格
            PdfPTable table = new PdfPTable(6);
            //设置每一列所占的长度
            table.setWidths(new float[]{10f, 20f, 20f, 10f, 15f, 15f,});
            table.setSpacingBefore(5);
            table.setPaddingTop(5);
            //设置表格具体宽度
            table.setTotalWidth(90);


            //==================================================================
            PdfPCell[] cellHeaders = new PdfPCell[6];
            cellHeaders[0] = new PdfPCell(new Phrase("编号", font));
            cellHeaders[1] = new PdfPCell(new Phrase("照片 ", font));
            cellHeaders[2] = new PdfPCell(new Phrase("物品名称", font));
            cellHeaders[3] = new PdfPCell(new Phrase("数量", font));
            cellHeaders[4] = new PdfPCell(new Phrase("物品特征", font));
            cellHeaders[5] = new PdfPCell(new Phrase("处理情况", font));
            /** 向表格填充数据 author:yyli Sep 15, 2010 */
            for (int i = 0; i < cellHeaders.length; i++) {
                /** 居中显示 author:yyli Sep 15, 2010 */
                cellHeaders[i].setHorizontalAlignment(Element.ALIGN_CENTER);
                /** 纵向居中显示 author:yyli Sep 15, 2010 */
                cellHeaders[i].setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cellHeaders[i]);
            }
            //=================================================================
            for (int i = 0; i < list.size(); i++) {
                /** 第0列 author:yyli Sep 15, 2010 */
                //填充第一列的编号并设置字体
                PdfPCell cell0 = new PdfPCell(new Phrase(String.valueOf(i + 1), font));
                cell0.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell0.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell0);
                //=================================================================
                //从第2列到第五列一次开始填充数据
                PdfPCell[] cell2_5 = new PdfPCell[5];
//                // 读取图片(参数为gif、jpg、png格式的图片都可以)，设置图片大小
//                Image image = Image.getInstance("D:/test/1.jpg");
//                // 设置图片的绝对大小，宽和高
//                image.scaleAbsolute(50f, 50f);
//                // 设置图片居中显示
//                image.setAlignment(Image.MIDDLE);
                //=====================================================================
                //String photoPath=list.get(i).getPicUrl();
                String photoPath = list.get(i).getPicUrl();
                if (!StringUtil.isEmpty(photoPath)) {
                    String headPicture = ConstantUtil.PHOTO_PATH + photoPath;
                    //String headPicture ="F:/data/photo/suspect/goods/1557142016953.png";
                    Image image = ConstantUtil.XSKYRESTORAGE ? Image.getInstance(new URL(photoPath)) :
                            Image.getInstance(headPicture);
                    // 设置图片居中显示
                    image.setAlignment(Image.MIDDLE);
                    image.scaleAbsolute(33f, 33f);
                    cell2_5[0] = new PdfPCell(image);
                }
                cell2_5[1] = new PdfPCell(new Phrase(list.get(i).getGoodsName(), font));
                cell2_5[2] = new PdfPCell(new Phrase(String.valueOf(list.get(i).getAmount()), font));
                cell2_5[3] = new PdfPCell(new Phrase(list.get(i).getEffectsDescribe(), font));
                if (list.get(i).getKeepMethed().equals(0)) {
                    cell2_5[4] = new PdfPCell(new Phrase("移交检察院", font));
                } else {
                    cell2_5[4] = new PdfPCell(new Phrase("发还被害人", font));
                }
                //给后五列设置字符集
                for (int n = 0; n < cell2_5.length; n++) {
                    cell2_5[n].setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell2_5[n].setVerticalAlignment(Element.ALIGN_MIDDLE);
                    //设置每个单元格的高度
                    cell2_5[n].setFixedHeight(50);
                    table.addCell(cell2_5[n]);
                }

            }
            //========================================================================================================================表格斜线
            //坐标起始位置
            float LEFT = document.left() + 50f;//表格起点x轴坐标
            float top = document.top() - list.size() * 50 - 37;//起点y轴坐标
            //坐标终点位置
            float x = document.right() - 150f;//表格终点x轴坐标
            float y = 450;//表格终点y坐标
            System.out.print(y + "------------------=========================-------------------------------");
            // int y=100+list.size()*50;
            int z = 50;//每列单元格高度
            float p = document.bottom() - top;//起点位置和终点位置,以便于填充高度为50的单元格
            for (int j = 0; j < (y / 50) * 6; j++) {
                PdfPCell cell1 = new PdfPCell();
                cell1 = new PdfPCell(new Phrase("", font));
                cell1.setFixedHeight(50);
                table.addCell(cell1);
            }

            PdfContentByte canvas = writer.getDirectContent();

            drawLine(canvas, LEFT, top, x, y);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String Date = sdf.format(new Date());
            //=================================================================最后一列中文
            PdfPCell cellLow = new PdfPCell(new Phrase("办案单位：" + organizationName + "处理物品,文件清单" + "    " +
                    "办案人:" + belongings.getPoliceName(), minimumFont));
            //左边的cell
            cellLow.setBorderWidthRight(0);    //边框宽度
            cellLow.setBorderWidthLeft(1);    //边框宽度
            cellLow.setBorderWidthBottom(1);    //边框宽度
            cellLow.setBorderWidthTop(1);    //边框宽度


            cellLow.setFixedHeight(20);
            cellLow.setColspan(5);
            table.addCell(cellLow);
            //==================================================================右下角时间设置
            PdfPCell cellRight = new PdfPCell(new Phrase(Date, minimumFont));
            //左边的cell
            cellRight.setBorderWidthRight(1);    //边框宽度
            cellRight.setBorderWidthLeft(0);    //边框宽度
            cellRight.setBorderWidthBottom(1);    //边框宽度
            cellRight.setBorderWidthTop(1);    //边框宽度
            cellRight.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); //水平偏右
            cellRight.setVerticalAlignment(PdfPCell.ALIGN_BOTTOM); //垂直居底
            cellRight.setBorderWidth(0);
            cellRight.setFixedHeight(20);
            cellRight.setColspan(5);
            table.addCell(cellRight);

            PdfPCell cell = new PdfPCell(new Phrase("本清单附卷。", minimumFont));
            document.add(table);
            //document.add(new Paragraph("11111111111111111111"));
            document.close();
            writer.close();


        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return returnPath;

    }

    @Override
    public int upDateGoods2(MultipartFile file, String id, String fileString) {
        boolean isHaveFile = file != null && file.getSize() > 0;
        // 表单上传文件或base64格式
        if (isHaveFile || !StringUtil.isEmpty(fileString)) {
            String path = ConstantUtil.PHOTO_PATH + "suspect" + File.separator + "returnGoods" + File.separator;

            String trueFileName = String.valueOf(System.currentTimeMillis());
            // 截取文件后缀

            byte[] bytes = null;
            //设置Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            if (isHaveFile) {
                try {
                    String fileName = file.getOriginalFilename();
                    String fileType = fileName.substring(fileName.lastIndexOf("."));
                    String filesPath = path + trueFileName + fileType;
                    filesPath = filesPath.replace("\\", "/");
                    bytes = file.getBytes();
                    metadata.setContentType(file.getContentType());
                    xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_PHOTO, filesPath, bytes, metadata);
                    if (belongingsMapper.upDateGoods(ConstantUtil.XSKY_PHOTO_URL + filesPath, id) > 0) {
                        log.info("上传成功");
                    } else {
                        log.error("上传失败");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("xsky上传失败");
                }
            } else {
                try {
                    String fileType = ".png";
                    String filesPath = path + trueFileName + fileType;
                    filesPath = filesPath.replace("\\", "/");
                    BASE64Decoder decoder = new BASE64Decoder();
                    String base64String = fileString.substring(fileString.indexOf(",") + 1);// 去掉头部（不能解析）
                    log.info("Base64解码后:\n" + base64String);
                    bytes = decoder.decodeBuffer(base64String);
                    for (int i = 0; i < bytes.length; ++i) {
                        if (bytes[i] < 0) {// 调整异常数据
                            bytes[i] += 256;
                        }
                    }
                    try {
                        metadata.setContentType(ContentType.IMAGE_JPEG.getMimeType());
                        xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_PHOTO, filesPath, bytes, metadata);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("xsky上传失败！");
                    }
                    if (belongingsMapper.upDateGoods(ConstantUtil.XSKY_PHOTO_URL + filesPath, id) > 0) {
                        log.info("上传成功");
                    } else {
                        log.error("上传失败");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return ResultEnum.FAIL.getCode();
                }
            }
            return ResultEnum.SUCCESS.getCode();
        }
        return ResultEnum.FAIL.getCode();

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Belongings addGoods2(MultipartFile file, String fileString, String suspectId) {
        log.info("service 事务测试start...");
        TSuspec tSuspec = new TSuspec();
        Belongings belongings = new Belongings();
        try {
//            tSuspec.setId(belongings.getSuspectId());
            TSuspec suspectState = tSuspecMapper.selectStatue(suspectId);
            if (!"8".equals(suspectState.getSuspectState())) {
                tSuspec.setSuspectState("3");
            } else {
                tSuspec.setSuspectState(suspectState.getSuspectState());
            }
            tSuspecMapper.updateState(tSuspec);
            boolean b = file != null && file.getSize() > 0;
            if (b || !StringUtil.isEmpty(fileString)) {
                String path = ConstantUtil.PHOTO_PATH + "suspect" + File.separatorChar + "goods" + File.separatorChar;
                // 文件原名称

                String trueFileName = String.valueOf(System.currentTimeMillis());

                byte[] bytes = null;
                //设置Metadata
                ObjectMetadata metadata = new ObjectMetadata();
                if (b) {
                    try {
                        String fileName = file.getOriginalFilename();
                        // 截取文件后缀
                        String fileType = fileName.substring(fileName.lastIndexOf("."));
                        String filesPath = path + trueFileName + fileType;
                        filesPath = filesPath.replace("\\", "/");
                        bytes = file.getBytes();
                        metadata.setContentType(file.getContentType());
                        xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_PHOTO, filesPath, bytes, metadata);
                        belongings.setSuspectId(suspectId);
                        belongings.setPicUrl(ConstantUtil.XSKY_PHOTO_URL + filesPath);
                        String id = StringUtil.generatorUUID();
                        belongings.setId(id);
                        if (belongingsMapper.insert(belongings) > 0) {
                            log.info("上传成功");
                        } else {
                            log.error("上传失败");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        log.error("xsky上传失败");
                        return null;
                    }
                } else {
                    try {
                        // 截取文件后缀
                        String fileType = ".png";
                        String filesPath = path + trueFileName + fileType;
                        filesPath = filesPath.replace("\\", "/");
                        BASE64Decoder decoder = new BASE64Decoder();
                        String base64String = fileString.substring(fileString.indexOf(",") + 1);// 去掉头部（不能解析）
                        log.info("Base64解码后:\n" + base64String);
//                    byte[] b = new byte[0];
                        bytes = decoder.decodeBuffer(base64String);
                        for (int i = 0; i < bytes.length; ++i) {
                            if (bytes[i] < 0) {// 调整异常数据
                                bytes[i] += 256;
                            }
                        }
                        try {
                            metadata.setContentType(ContentType.IMAGE_JPEG.getMimeType());
                            xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_PHOTO, filesPath, bytes, metadata);

                        } catch (Exception e) {
                            e.printStackTrace();
                            log.error("xsky上传失败！");
                        }
                        belongings.setSuspectId(suspectId);
                        belongings.setPicUrl(ConstantUtil.XSKY_PHOTO_URL + filesPath);
                        String id = StringUtil.generatorUUID();
                        belongings.setId(id);
                        if (belongingsMapper.insert(belongings) > 0) {
                            log.info("上传成功");
                        } else {
                            log.error("上传失败");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
                return belongings;
            }
            return null;
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            //抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }

    }


}


